<!-- 关键物料信息弹窗 -->
<template>
  <el-dialog append-to-body :title="title" :visible.sync="visible" @close="close" width="60%" top="5vh">
    <avue-crud
      ref="crud"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :option="tableOption"
      :page.sync="page"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @row-click="rowClick"
      @row-dblclick="rowDbclick"
    >
      <template slot-scope="{ row }" slot="quantity">
        <el-input-number size="mini" style="width: 120px" v-model="row.quantity" controls-position="right" :min="0"> </el-input-number>
      </template>
      <template slot="menuLeft" v-if="!readOnlyPage">
        <el-button type="primary" size="small" @click="addMaterial">添加物料</el-button>
      </template>
      <template slot="menuLeft" v-if="!readOnlyPage">
        <el-button type="primary" size="small" @click="addBom">添加BOM</el-button>
      </template>
      <template slot="menuLeft" v-if="!readOnlyPage">
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>
    <div slot="footer" class="dialog-footer" v-if="!readOnlyPage">
      <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm">保 存</el-button>
      <el-button size="small" icon="el-icon-circle-close" @click="close">取 消</el-button>
    </div>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="commonTableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="addTableOption" @getSelectedRows="getAddSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
export default {
  name: 'KeyPartModal',
  components: {
    CommonModalTemplate,
    GlobalModalTemplate
  },
  props: {
    config: {
      require: true,
      default: () => {}
    }
  },
  data() {
    return {
      selectionList: [],
      visibile: false,
      title: '',
      loading: false,
      data: [],
      page: {
        pageSize: 1000,
        currentPage: 1,
        total: 0
      },
      modalName: '',
      addTableOption: {},
      tableOption: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        addBtn: false,
        delBtn: true,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 80,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        selection: true,
        column: [
          {
            label: '物料编码',
            prop: 'partNo',
            slot: true
          },
          {
            label: '物料名称',
            prop: 'partName',
            slot: true
          },
          {
            label: '物料规格',
            prop: 'partModel',
            slot: true
          },
          // {
          //   label: '扫描类型',
          //   prop: 'transType',
          //   slot: true
          // },
          // {
          //   label: '组装条码',
          //   prop: 'assemblyCode',
          //   slot: true
          // },
          // {
          //   label: '验证代码',
          //   prop: 'principal??'
          // },
          {
            label: '数量',
            prop: 'quantity',
            type: 'number'
          }
        ]
      },
      commonTableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapState({
      currentStationInfo: (state) => state.design.currentStationInfo
    }),
    routePath() {
      return this.$route.path;
    },
    // 查看页面 只读
    readOnlyPage() {
      if (this.routePath.endsWith('pdesign') || this.routePath.endsWith('gdesign')) {
        return false;
      } else {
        return true;
      }
    },
    // 是否工单工艺路线设计器
    isGdEditorPage() {
      if (this.$route.path.endsWith('pdesign') || this.$route.path.endsWith('pread')) {
        return false;
      } else if (this.$route.path.endsWith('gdesign') || this.$route.path.endsWith('gread')) {
        return true;
      }
    }
  },
  watch: {
    config: {
      handler(value) {
        let copyData = this._cloneDeep(value);
        this.data = copyData.data;
        this.title = copyData.title;
        this.visible = copyData.visible;
        this.loading = copyData.loading;
      },
      deep: true
    }
  },
  mounted() {
    this.data = this.config.data;
    this.title = this.config.title;
    this.visible = this.config.visible;
    this.loading = this.config.loading;
  },
  methods: {
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let partMasterIds = this.selectionList.map((s) => s.partMasterId);
        let partNames = this.selectionList.map((s) => s.partName).join(',');
        this.data = this.data.filter((d) => !partMasterIds.includes(d.partMasterId));
        this.$message({
          type: 'success',
          message: `物料名称为${partNames}删除成功!`
        });
      });
    },
    selectionChange(list) {
      this.selectionList = list;
    },

    // 添加物料
    addMaterial() {
      this.modalName = 'tjwlModal';
      this.visibile = true;
      this.addTableOption = {
        modalTitle: '添加物料信息',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        query: {
          // semifinished: false
          // partType: 'SEMIFINISHED'
        },
        rowSelectionType: 'multiple',
        menuWidth: 100,
        templateName: 'PARTMASTER'
      };
    },
    getAddSelectedRows(rowData) {
      switch (this.modalName) {
        case 'tjwlModal':
          let repeatData = rowData.filter((row) => this.data.map((d) => d.partMasterId || d.id).includes(row.id)).map((r) => r.name);
          let noRepeatData = rowData.filter((row) => !this.data.map((d) => d.partMasterId).includes(row.id));
          if (repeatData && repeatData.length > 0) {
            this.$message.warning(`物料${repeatData.join(',')}已添加，请勿重复操作`);
          }
          let data = noRepeatData.map((d) => {
            return {
              quantity: 0,
              partName: d.name,
              partNo: d.partNo,
              partModel: d.partModel,
              partMasterId: d.id
            };
          });
          this.data = this.data.concat(data);
          this.visibile = false;
          break;
        default:
          break;
      }
    },
    // 添加BOM
    addBom() {
      this.$refs.commonModalTemplate.showModal();
      let url = '';
      if (this.isGdEditorPage) {
        url = this.$route.query.bomId ? `/api/mes-admin/bom/detail/part-page?bomId=${this.$route.query.bomId}` : `/api/mes-admin/bom/detail/part-page`;
      } else {
        url = this.$route.query.bomId ? `/api/mes-admin/bom/detail/part-page?bomId=${this.$route.query.bomId}` : `/api/mes-admin/bom/detail/part-page`;
      }
      this.commonTableOption = {
        modalTitle: '选择BOM物料信息（双击进行选择）',
        url: url,
        isPage: true,
        index: true,
        selection: true,
        rowSelectionType: 'multiple',
        titleInfo: 'keyPart',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '用量',
            prop: 'unitQty'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      let repeatData = rowData.filter((row) => this.data.map((d) => d.partMasterId || d.id).includes(row.id)).map((r) => r.name);
      let noRepeatData = rowData.filter((row) => !this.data.map((d) => d.partMasterId).includes(row.id));
      if (repeatData && repeatData.length > 0) {
        this.$message.warning(`物料${repeatData.join(',')}已添加，请勿重复操作`);
      }
      let data = noRepeatData.map((d) => {
        return {
          quantity: d.unitQty,
          partName: d.name,
          partNo: d.partNo,
          partModel: d.partModel,
          partMasterId: d.id
        };
      });
      this.data = this.data.concat(data);
    },
    submitForm() {
      if (this.data.length > 0) {
        let hasQuantity = this.data.every((d) => d.quantity > 0);
        if (!hasQuantity) {
          this.$message.warning('物料数量不能为0！');
          return;
        }
      }
      let siteId = localStorage.getItem('saber-siteId');
      let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
      let processMaterialControlList = this.data.map((d) => {
        return {
          id: d.id,
          controlType: 'PROCESS',
          siteId: siteId,
          partModel: d.partModel,
          partName: d.partName,
          partMasterId: d.partMasterId, // 物料id
          partNo: d.partNo, //物料编码
          quantity: d.quantity, //数量
          tenantId: tenantId
        };
      });
      this.$emit('changeProcessMaterialControlList', processMaterialControlList);
      this.close();
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    close() {
      this.$emit('close');
    }
  }
};
</script>
